﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;

using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.IO;
using FlightSearchServer;
using System.Threading;

namespace TicketSellingServer
{
    public static class ServerData
    {
        public static void ParseArgs(string[] args)
        {
            _Port = args[0];
            _FlightSearchServURI = args[1];
            _InputFileName = args[2];
            _SellerName = args[3];
        }

        public static void ParseInputFile()
        {
            string line;
            StreamReader file = new StreamReader(_InputFileName);
            while ((line = file.ReadLine()) != null)
            {
                var lineArray = line.Split(' ');
                SellerFlightInfo ticket = new SellerFlightInfo();
                ticket.Company = _SellerName;
                ticket.Flight = lineArray[0];
                ticket.Source = lineArray[1];
                ticket.Destination = lineArray[2];
                ticket.Date = lineArray[3];
                ticket.Seats = lineArray[4];
                ticket.Price = lineArray[5];
                ticket.ReservedSeats = 0;
                ticketDataBase.Add(ticket);
            }
            file.Close();
        }
      
        public static string _Port = "";
        public static string _FlightSearchServURI = "";
        public static string _InputFileName = "";
        public static string _SellerName = "";
        public static SellerFlightsList ticketDataBase= new SellerFlightsList();
        //(stringReservationID, Flight+" "+Date)
        public static Dictionary<string, string> ReservationDict = new Dictionary<string, string>();
        public static int ReservationID = 0;

        //lock needed for proper parallel access to ticketDataBase
        public static ReaderWriterLock ticketDataBaseLock = new ReaderWriterLock();
    }

    class HostingProgram
    {
        static void Main(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("Please provide 4 arguments");
                return;
            }
            ServerData.ParseArgs(args);
            ServerData.ParseInputFile();

            string sellerUri = "http://localhost:" + ServerData._Port + "/Services";

            try
            {
                using (ServiceHost host = new ServiceHost(typeof(TicketSellingService), new Uri(sellerUri)))
                {
                    try
                    {
                        host.Open();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error occured: {0}", e.Message);
                        Console.WriteLine("Can't start service, exiting");
                        return;
                    }


                    Console.WriteLine("Ticket selling service:    {0} ", sellerUri);
                    Console.WriteLine("Connecting to " + ServerData._FlightSearchServURI);

                    try
                    {
                        WebChannelFactory<IFlightSearchServiceSellers> channelFactory =
                                    new WebChannelFactory<IFlightSearchServiceSellers>(new WebHttpBinding(), new Uri("http://" + ServerData._FlightSearchServURI));
                        IFlightSearchServiceSellers channel = channelFactory.CreateChannel();

                        using (new OperationContextScope((IContextChannel)channel))
                        {
                            channel.AddNewSeller(ServerData._SellerName, sellerUri + "/TicketSellingService");
                        }


                        Console.WriteLine("Succesfully register in search service");
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("An error occurred, can't register in search service");
                    }

                    Console.WriteLine("TicketSellingServer of '{0}' company is running. Press return to exit.", ServerData._SellerName);
                    // keep the process alive
                    Console.ReadLine();
                    //server runs here

                    try
                    {
                        WebChannelFactory<IFlightSearchServiceSellers> channelFactory =
                                    new WebChannelFactory<IFlightSearchServiceSellers>(new WebHttpBinding(), new Uri("http://" + ServerData._FlightSearchServURI));
                        IFlightSearchServiceSellers channel = channelFactory.CreateChannel();

                        using (new OperationContextScope((IContextChannel)channel))
                        {
                            channel.RemoveSeller(ServerData._SellerName);
                        }


                        Console.WriteLine("Succesfully deregistered from search service");
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("An error occurred, can't deregister from search service");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error occured: {0}, exiting", e.Message);
            }
        }
    }
}

